package com.spsyry.pay.config;

import com.spsyry.pay.constatant.RabbitmqConstantCompany;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class RabbitmqConfigCompany {

    //队列
    @Bean
    public Queue createQueue() {
        return new Queue(RabbitmqConstantCompany.MQ_QUEUE_NAME, true);
    }
    //交换机
    @Bean
    public DirectExchange createExchange(){
        return new DirectExchange(RabbitmqConstantCompany.MQ_EXCHANGE_NAME);
    }
    //队列绑定到交换机，附带路由建
    @Bean
    public Binding createBinding(){
        return BindingBuilder.bind(this.createQueue()).to(this.createExchange()).with(RabbitmqConstantCompany.MQ_ROUTING_KEY);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        //交换机没有达到队列，启用ReturnsCallback
        rabbitTemplate.setMandatory(true);
        //开启生产者确认 确认交换机的exchange
        rabbitTemplate.setConfirmCallback(((correlationData, ack, cause) -> {
            if (ack){
                System.out.println("发送消息成功="+correlationData.getId());
            }else {
                System.out.println("消息发送失败，原因："+cause+",消息ID："+correlationData.getId());
                //TODO:保存到数据库
            }
        }));
        //开启生产者回退 queue nack
        rabbitTemplate.setReturnsCallback(returned->{
            System.out.println("错误码 replyCode="+returned.getReplyCode());
            System.out.println("原因 text="+returned.getReplyText());
            System.out.println("交换机 exchange="+returned.getExchange());
            System.out.println("routingKey="+returned.getRoutingKey());
            System.out.println("消息 ="+new String(returned.getMessage().getBody()));
        });

        return rabbitTemplate;

    }
}
